using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using SlimDX.DirectInput;
using GameControllerState = SlimDX.DirectInput.JoystickState; 

namespace test3d
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        SpriteFont font;
        GameControllerState controllerState;
        Matrix view;
        Matrix projection;
        Ship ship;
        DirectInput input;
        GameController controller;
        float anglez, angley, anglex;
        Vector3 pos;
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            anglez = 0;
            anglex = 0;
            angley = 0;
            pos = new Vector3(0, 0, 0);
            input = new DirectInput();
            controller = new GameController(input, this, 0);
            ship = new Ship(new Vector3(0, 0, 0));
            view = Matrix.CreateLookAt(new Vector3(30, 30, 30), new Vector3(0, 0, 0), Vector3.UnitY);
            projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45), 800f / 480f, 0.1f, 1000f);
            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            font = Content.Load<SpriteFont>("font");
            ship.setModel(Content.Load<Model>("ship2"));
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
            controller.Release();
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();
            anglez = 0;
            anglex = 0;
            angley = 0;
            pos = new Vector3(0, 0, 0);
            Vector3 oldpos = ship.orientation.Translation;
            Microsoft.Xna.Framework.Input.KeyboardState keyboard = Microsoft.Xna.Framework.Input.Keyboard.GetState();
            controllerState = controller.GetState();
            if (keyboard.IsKeyDown(Keys.A)) angley += 3f;
            if (keyboard.IsKeyDown(Keys.D)) angley -= 3f;
            if (keyboard.IsKeyDown(Keys.Left)) anglez += 3f;
            if (keyboard.IsKeyDown(Keys.Right)) anglez -= 3f;
            if (keyboard.IsKeyDown(Keys.Up)) anglex -= 3f;
            if (keyboard.IsKeyDown(Keys.Down)) anglex += 3f;
            if (controllerState != null)
            {
                if (controllerState.RotationZ > 0)
                {
                    anglex += (float)((controllerState.RotationZ) / 1000f);
                }
                else
                {
                    anglex += (float)(controllerState.RotationZ / 1000f);
                }
                angley += (float)(controllerState.Z / 1000f);
                if (controllerState.GetPointOfViewControllers()[0] / 9000 == 1)
                {
                    anglez -= 5f;
                }
                if (controllerState.GetPointOfViewControllers()[0] / 9000 == 3)
                {
                    anglez += 5f;
                }

                if (controllerState.GetPointOfViewControllers()[0] / 9000 == 0 && controllerState.GetPointOfViewControllers()[0] % 9000 == 0)
                {
                    pos += ship.orientation.Up;
                }
                if (controllerState.GetPointOfViewControllers()[0] / 9000 == 2)
                {
                    pos -= ship.orientation.Up;
                }
                pos -= ship.orientation.Forward * (float)(controllerState.Y / 5000f);
                pos += ship.orientation.Right * (float)(controllerState.X / 5000f);
            }
            if (keyboard.IsKeyDown(Keys.W)) pos += ship.orientation.Forward;
            if (keyboard.IsKeyDown(Keys.S)) pos -= ship.orientation.Forward;
            if (keyboard.IsKeyDown(Keys.Q)) pos -= ship.orientation.Right;
            if (keyboard.IsKeyDown(Keys.E)) pos += ship.orientation.Right;
            if (keyboard.IsKeyDown(Keys.Space)) pos += ship.orientation.Up;
            if (keyboard.IsKeyDown(Keys.X)) pos -= ship.orientation.Up;
            ship.orientation *= Matrix.CreateFromAxisAngle(ship.orientation.Forward, MathHelper.ToRadians(anglez));
            ship.orientation *= Matrix.CreateFromAxisAngle(ship.orientation.Right, MathHelper.ToRadians(anglex));
            ship.orientation *= Matrix.CreateFromAxisAngle(ship.orientation.Up, MathHelper.ToRadians(angley));
            ship.orientation.Translation = oldpos;
            ship.orientation *= Matrix.CreateTranslation(pos);
            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.White);
            spriteBatch.Begin();
            spriteBatch.End();

            DrawModel(ship.model, ship.orientation, view, projection);

            base.Draw(gameTime);
        }

        private void DrawModel(Model model, Matrix world, Matrix view, Matrix projection)
        {
            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.World = ship.orientation;
                    effect.View = view;
                    effect.Projection = projection;
                }

                mesh.Draw();
            }
        }
    }
}
